<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>用户主页</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{layui/css/layui.css}"  media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>
<!--<form class="layui-form" action="">-->
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">序号：</label>
            <div class="layui-input-inline">
                <input type="text" name="uid" id="uidReload" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">账号：</label>
            <div class="layui-input-inline">
                <input type="text" name="username" id="usernameReload" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">密码：</label>
            <div class="layui-input-inline">
                <input type="text" name="password"  id="passwordReload" class="layui-input">
            </div>
        </div>
        <!--<div class="layui-inline"> &lt;!&ndash; 注意：这一层元素并不是必须的 &ndash;&gt;
            <label class="layui-form-label">时间：</label>
            <div class="layui-input-inline">
            <input type="text" class="layui-input" id="test1">
            </div>
        </div>-->
        <div class="layui-inline">
            <div class="layui-input-inline">
                <button type="submit" class="layui-btn" data-type="reload" id="search">搜索</button>
                <button class="layui-btn"  type="reset" id="reset">重置</button>
            </div>
        </div>
    </div>

<table class="layui-hide" id="test" lay-filter="test"></table>

<script type="text/html" id="toolbarDemo">

    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="addUser">增加</button>
        <!--<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>-->
        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
    </div>
</script>


<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>


<script th:src="@{layui/layui.js}" charset="utf-8"></script>
<script th:src="@{lib/layui-v2.5.5/layui.js}" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
<!--<script>
    layui.use('laydate', function(){
        var laydate = layui.laydate;

        //执行一个laydate实例
        laydate.render({
            elem: '#test1' //指定元素
        });
    });
</script>-->

<script type="text/javascript" src="layui/jquery.min.js"></script>

<script>
    layui.use(['table','form'], function(){

        var table = layui.table;
        var url = '/user';
        var form = layui.form;
        //温馨提示：默认由前端自动合计当前行数据。从 layui 2.5.6 开始： 若接口直接返回了合计行数据，则优先读取接口合计行数据。
        //详见：https://www.layui.com/doc/modules/table.html#totalRow
        table.render({
            elem: '#test'  //绑定元素
            ,url:url  //数据来源
            ,toolbar: '#toolbarDemo'   //映射绑定
            ,title: '学生数据表'   //导出数据所使用的的名单
            ,totalRow: true
            ,limits:[10,20,40,80,30000]
            ,cols: [
                [
                    {type: 'checkbox', fixed: 'left'}
                    ,{field:'uid', title:'序号', width:80, fixed: 'left', unresize: true, sort: true} /* totalRowText: '合计'*/
                    ,{field:'admin', title:'用户类型', width:200}
                    ,{field:'username', title:'账号', width:200, sort: true}
                    ,{field:'password', title:'密码', width:200}
                    ,{field:'status', title:'状态', width:100,
                        templet:function(res){
                            if(res.status==='停用'){
                                return '<a class="layui-btn layui-btn-danger layui-btn-xs">停用</a>';
                            }else if(res.status==='正常'){
                                return '<a class="layui-btn layui-btn-xs">正常</a>';
                            }
                        }}
                    ,{fixed: 'right', title:'操作', toolbar: '#barDemo'}
                ]
            ]
            ,page: true //分页
            ,id:'testReload' //重新加载实现搜索功能
        });

        var $ = layui.$,active = {
            reload:function(){
                var uidReload = $('#uidReload');
                var usernameReload = $('#usernameReload');
                var passwordReload = $('#passwordReload');
                var index = layer.msg("查询中，请稍后...",{
                    icon:16,
                    time:false,
                    shade:0
                });
                setTimeout(function(){
                    table.reload('testReload',{
                        page:{
                            curr:1
                        }
                        ,where:{
                            /*key:{*/
                                uid:uidReload.val(),
                                username:usernameReload.val(),
                                password:passwordReload.val()
                            /*}*/
                        },
                        method:'POST',
                        url:'user/searchUser'
                    });
                    layer.close(index);
                },800);

            }
        };

        $('#search').on('click',function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this):'';
        })

        $('#reset').on('click',function(){
            $('#uidReload').val('');
            $('#usernameReload').val('');
            $('#passwordReload').val('');
        });


        //工具栏事件
        table.on('toolbar(test)', function(obj){
            var data1 = obj.data;
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){   //当前点击
                /*case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;*/
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选': '未全选')
                    break;
                case 'addUser':
                    var index = layer.open({
                        title: '添加用户',
                        type: 2, //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                        shade:0.2,
                        maxmin: true,
                        shadeClose : true,
                        area :['50%','50%'],
                        content: '/addUser',
                    });
                    $(window).on("resize",function(){
                        layer.full(index)
                    });
                    return false;
                    break;
            };
        });

        //监听工具条
        table.on('tool(test)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.msg('删除'+data.uid);
                layer.confirm('真的删除行么', function(index){
                    //直接向服务器发送删除请求
                    $.ajax({
                        url:'user/deleteUserById',
                        type:'POST',
                        data:{uid:data.uid},
                        success: function(result){
                            if(result.code===200){
                                layer.close(index);
                                layer.msg("删除成功！");
                                parent.window.location.reload();
                            }else{
                                layer.msg("删除失败！");
                            }
                        }
                    })
                });
            } else if(obj.event === 'edit'){
                layer.msg("修改"+data.uid);
                //打开弹出层
                var index =layer.open({
                    type: 1,
                    title: "修改用户",
                    shade:0.2,
                    maxmin: true,
                    shadeClose : true,
                    area :['50%','50%'],
                    content: $("#userUpdateTest")
                });
                $(window).on("resize",function(){
                    layer.full(index)
                });
                //方式1通过Id查询该记录，方式2，获取该选中记录，然后data渲染。
                setFormValue(obj,data);
            }
        });


        function setFormValue(obj,data){
            console.log(data);
            data.admin = "0";
            if(data.status==="停用"){
                data.status='';
            }

            console.log(data);
            form.val("updateBtn",{
                "uid":data.uid,
                "username":data.username,
                "password":data.password,
                "status":data.status,
                "admin":data.admin
            });
          form.on('submit(updateBtn)',function(data){
              var datas = data.field;
              console.log(datas);
              if(datas.status==="on"){
                  datas.status=1;
              }
              //向后端发送数据并进行添加操作
              $.ajax({
                  url:"user/updateUserSubmit",
                  type: "POST",
                  data:datas,
                  success:function(result){
                      //将json对象转成string
                      // result = JSON.parse(result);
                      if(result.code==200){
                          layer.msg("修改成功！",{
                              icon:6,
                              time:500
                          },function(){
                              parent.window.location.reload();//重新加载页面
                              var iframeIndex = parent.layer.getFrameIndex(window.name);
                              parent.layer.close(iframeIndex);
                          });
                      }else{
                          layer.msg("修改失败！");
                      }
                  }
              })

          })


        };



    });
</script>


    <div class="layui-form layuimini-form" id="userUpdateTest" style="display:none" lay-filter="updateBtn">
        <input type="hidden" name="uid" />
        <div class="layui-form-item">
            <label class="layui-form-label required">用户账号</label>
            <div class="layui-input-block">
                <input type="text" name="username" lay-verify="required" lay-reqtext="账号不能为空" placeholder="请输入用户名" value="" class="layui-input">
                <!--<tip>填写自己管理账号</tip>-->
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label required">用户密码</label>
            <div class="layui-input-block">
                <input type="text" name="password" lay-verify="required" lay-reqtext="密码不能为空" placeholder="请输入密码" value="" class="layui-input">
            </div>
        </div>

        <div class="layui-form-input">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
                <input type="checkbox" name="status" lay-skin="switch" lay-text="正常|停用">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label required">用户类型</label>
            <div class="layui-input-block">
                <input type="radio" name="admin" value="0" title="普通管理者" checked="">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-normal" lay-submit lay-filter="updateBtn">确认修改</button>
            </div>
        </div>
    </div>





</body>
</html>